﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using FileSystem.Models;
using FileSystem.Services.IServices;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace FileSystem.ViewModels {
    /// <summary>
    /// 物理磁盘块页ViewModel
    /// </summary>
    public class PhysicalDiskBlockPageViewModel : ViewModelBase {
        // ******** 构造函数
        /// <summary>
        /// 系统接口
        /// </summary>
        private ISystem _system;

        /// <summary>
        /// 磁盘块信息存储
        /// </summary>
        private IDiskBlockStorage _diskBlockStorage;

        /// <summary>
        /// 物理磁盘块页ViewModel
        /// </summary>
        public PhysicalDiskBlockPageViewModel(ISystem system,
            IDiskBlockStorage diskBlockStorage) {
            _system = system;
            _diskBlockStorage = diskBlockStorage;
        }

        // ******** 绑定属性
        /// <summary>
        /// 物理块
        /// </summary>
        public ObservableCollection<ColorAndFont> PhysicalDiskBlocks { get; } =
            new ObservableCollection<ColorAndFont>();

        // ******** 绑定命令

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand =
                new RelayCommand(async () =>
                    await PageAppearingCommandFunction()));

        public async Task PageAppearingCommandFunction() {
            if (_isLoaded)
                return;
            _isLoaded = true;

            var list = await _diskBlockStorage.GetDiskBlocks();
            foreach (var diskBlock in list)
                if (diskBlock.PhysicalBlockType ==
                    (int) DiskBlockConst.Type.Null)
                    PhysicalDiskBlocks.Add(new ColorAndFont {
                        Color = "Green",
                        Font = Convert.ToString(diskBlock.PhysicalBlockNumber)
                    });
                else
                    PhysicalDiskBlocks.Add(new ColorAndFont {
                        Color = "Red",
                        Font = Convert.ToString(diskBlock.PhysicalBlockNumber)
                    });
        }

        // ******** 公开变量

        // ******** 私有变量

        /// <summary>
        /// 页面是否已经加载
        /// </summary>
        private volatile bool _isLoaded;
    }
}